import ZkSearcher from '@/components/zk-searcher'
import ZkTable    from '@/components/zk-table'
import ZkItemPool from '@/components/zk-item-pool'

export default {
	components: { ZkSearcher, ZkTable, ZkItemPool },
	data() {
		return {
			service     : {},
			actions     : [],
			columns     : [],
			query       : {},
			model       : {},
			selectedRows: [],
			visible     : false,
			isAddModal  : true,
		}
	},
	computed  : {
		tableColumns() {
			return this.columns.filter(e => e.table)
		},
		formColumns() {
			return this.columns.filter(e => e.form)
		},
		searchColumns() {
			return this.columns.filter(e => e.search)
		},
		modalTitle() {
			return this.isAddModal ? '添加' : '编辑'
		}
	},
	watch     : {
		visible(v) {
			if (!v && this.$refs.modelForm) {
				this.$refs.modelForm.clearValidate()
				this.$refs.modelForm.resetFields()
				this.model = {}
			}
		}
	},
	methods   : {
		onSelection(rows) {
			this.selectedRows = rows
		},
		handleAdd(model = {}) {
			this.isAddModal = true
			this.model = { ...model }
			this.visible = true
		},
		handleUpdate(model = {}) {
			this.isAddModal = false
			if (this.selectedRows.length === 1) {
				const [selected = {}] = this.selectedRows
				if (selected.id) {
					this.model = { ...this.model, ...selected, ...model }
					this.visible = true
				}
			}
			else if (this.selectedRows.length > 1) {
				this.$message.warning('请选择唯一一条记录')
			}
			else {
				this.$message.warning('请选择要编辑的记录')
			}
		},
		async submit() {
			this.$refs.modelForm.validate(async (valid) => {
				if (valid) {
					let ret = null
					if (this.isAddModal) {
						delete this.model.id
						ret = await this.service.addItem(this.model)
					}
					else {
						ret = await this.service.editItem(this.model)
					}
					if (ret) {
						this.reload()
						this.model = {}
						this.visible = false
					}
				}
			})
		},
		handleDelete() {
			if (this.selectedRows.length) {
				this.$alert(`确认删除 ${ this.selectedRows.length } 条记录`, '确认删除', {
					confirmButtonText: '确定',
					callback         : async action => {
						console.log(action)
						if (action === 'confirm') {
							const ids = this.selectedRows.map(e => e.id).join(';')
							await this.service.delItemByIds(ids) && this.reload()
						}
					}
				})
			}
			else {
				this.$message.warning('请选择要删除的记录')
			}
		},
		reload() {
			this.query = { ...this.query }
		},
	}
}
